const express = require('express')
const router = express.Router()
const {getDb, saveDb} = require('../utils/db')

router.get('',async (req,res)=>{
  try {
    const db = await getDb("../mock/epic.json");
    res.json(db)
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
})

router.post('',async (req,res)=>{
  try {
    const newEpic = req.body;
    if(!newEpic.name){
      return res.status(401).json({
        error:'请添加项目名'
      })
    } 
    let epcis =await getDb("../mock/epic.json")
    let lastEpic = epcis[epcis.length -1]
    if(lastEpic === undefined){
      console.log('空数据');
      lastEpic = new Object()
      lastEpic.ownerId = 193361109
    }
    newEpic.id = lastEpic.id? lastEpic.id +1 : 1;
    newEpic.created = new Date().getTime()
    newEpic.projectId = +newEpic.projectId
    epcis.push(newEpic)

    await saveDb(epcis,"../mock/epic.json")
    epcis =await getDb("../mock/epic.json")

    res.status(200).json(epcis)
  } catch (error) {
    res.status(500).json({
      error:error.message
    })
  }
})


router.delete('/:id',async (req,res)=>{
  const epics =await getDb("../mock/epic.json")
  const getEpicInedx = epics.findIndex(epic => epic.id === +req.params.id)
  console.log(getEpicInedx);
  if(getEpicInedx ===-1){
    return res.status(402).json('找不到要删除的内容')
  }
  epics.splice(getEpicInedx,1)
  await saveDb(epics,"../mock/epic.json")
  res.status(200).send('删除成功')
})
module.exports = router